package com.handsome.service.impl;

import com.handsome.dao.HsDictionaryMapper;
import com.handsome.entity.HsDictionary;
import com.handsome.service.DictionaryService;
import com.handsome.utils.Result;
import com.handsome.utils.ResultGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class DictionaryServiceImpl implements DictionaryService {

    @Autowired
    private HsDictionaryMapper hsDictionaryMapper;

    @Override
    public List<HsDictionary> getAllDictionary() {

        return hsDictionaryMapper.selectAll();
    }

    @Override
    public List<HsDictionary> getDictionaryById(Integer id) {
        HsDictionary dictionary = new HsDictionary();
        dictionary.setParentId(id);
        return hsDictionaryMapper.select(dictionary);
    }

    @Override
    public List<HsDictionary> getAllDictionaryExcludeCurrentId(Integer id) {
        Example example = new Example(HsDictionary.class);
        example.createCriteria().andNotEqualTo("id", id);
        return hsDictionaryMapper.selectByExample(example);

    }

    @Override
    public Result addDictionaryItem(HsDictionary dictionary) {
        dictionary.setCreateUserId(1);

        // 修改
        if (dictionary.getId() != null) {
            int row = hsDictionaryMapper.updateByPrimaryKey(dictionary);
            if (row <= 0) {
                return ResultGenerator.genFailResult("添加失败请稍后再试");
            }
        }
        // 添加
        else {
            int row = hsDictionaryMapper.insert(dictionary);
            if (row <= 0) {
                return ResultGenerator.genFailResult("添加失败请稍后再试");
            }
        }


        return ResultGenerator.genSuccessResult();
    }

    @Override
    public Result delDictionaryItem(Integer id) {

        // 查看该字典项下有没有子数据
        HsDictionary dictionary = new HsDictionary();
        dictionary.setParentId(id);
        if (hsDictionaryMapper.selectCount(dictionary) > 0) {
            return ResultGenerator.genFailResult("该字典项下还有子数据,不能删除");
        }

        if (hsDictionaryMapper.deleteByPrimaryKey(id) > 0){
            return ResultGenerator.genSuccessResult();
        }

        return ResultGenerator.genFailResult("删除失败请稍后再试");
    }
}
